const express = require("express");
const formidable = require("formidable");
const path = require("path");
const md5 = require("md5");
const UserModel = require("../db/models/UserModel");

//声明检测 token 的中间件函数
let checkTokenMiddleware = require('../middlewares/checkTokenMiddleware');

const router = express.Router();
//设置使用中间件
// router.use(checkTokenMiddleware);

//声明路由规则   接口   postman
router.post("/user", (req, res) => {
  //创建 formidable form 对象
  const form = formidable({
    multiples: true,
    // uploadDir 对应的文件夹, 需要手动创建
    uploadDir: path.resolve(__dirname, "../public/uploads"), //选择绝对路径
    keepExtensions: true, //保留文件原始的扩展名   就是文件名后缀
  });
  //解析表单数据
  form.parse(req, async (err, fields, files) => {
    if (err) {
      console.log(err);
      return res.send("错误");
    }
    try {
      //表单验证
      //1. 格式是否正确
      //2. 两次密码是否一致
      //3. 用户名是否可用
      //4. 检测用户名内容是否合规
      if (fields.pwd !== fields.repwd) {
        //返回 JSON
        return res.json({
          code: "1001",
          msg: "两次密码不一致",
          data: null,
        });
      }

      //用户名格式显示 4-18 的非空白字符
      let reg = /^\S{4,18}$/;
      if (!reg.test(fields.uname)) {
        return res.json({
          code: "1002",
          msg: "用户名格式不正确",
          data: null,
        });
      }

      //插入数据库之前 检测该用户名是否已经存在
      let count = await UserModel.count({ uname: fields.uname });
      //判断
      if (count > 0) {
        return res.json({
          code: "1003",
          msg: "该用户名已经存在, 请更换",
          data: null,
        });
      }

      //拼接图片的访问路径
      let filePath = files.profile.filepath;
      let profile = filePath.split("public").pop().replaceAll("\\", "/");

      //将数据插入到数据库中
      let data = {
        uname: fields.uname,
        pwd: md5(fields.pwd), //密码要加密
        profile,
      };
      //插入数据库
      let newUser = await UserModel.create(data); //UserModel.create(data, (err, data) => {})
      //响应成功的结果
      return res.json({
        code: "0000",
        msg: "添加成功",
        data: newUser,
      });
    } catch (e) {
      return res.json({
        code: "2001",
        msg: "数据库操作失败~",
        data: null,
      });
    }
  });
});

/**
 * 批量获取用户
 * /user?page=1   =>   1-10  =>   skip(0).limit(10)
 * /user?page=2   =>   11-20 =>   skip(10).limit(10)
 * /user?page=3   =>   21-30 =>   skip(20).limit(10)
 * /user?page=n   =>         =>   skip((n-1) * 10).limit(10)
 */
router.get("/user", async (req, res) => {
  //查询字符串 实现分页的功能
  let page = req.query.page;
  page = page || 1;//默认值 1
  //获取开始的标记
  let skip = (page - 1) * 10;
  try {
    //获取用户集合中的总数
    let count = await UserModel.count();
    //读取所有的用户
    let users = await UserModel.find().skip(skip).limit(10);
    res.json({
      code: "0000",
      msg: "获取成功",
      data: {
        users: users,
        count: count
      },
    });
  } catch (e) {
    return res.json({
      code: "2001",
      msg: "数据库操作失败~",
      data: null,
    });
  }
});

/**
 * 获取单个用户
 */
router.get("/user/:id", async (req, res) => {
  //获取请求 id
  let id = req.params.id;
  //判断
  if (!id) {
    return res.json({
      msg: "id参数缺失",
      code: "1004",
      data: null,
    });
  }
  try {
    //根据 id 查询数据库, 获取用户数据
    let user = await UserModel.findOne({ _id: id });
    //响应结果
    res.json({
      code: "0000",
      msg: "获取成功",
      data: user,
    });
  } catch (e) {
    return res.json({
      code: "2001",
      msg: "数据库操作失败~",
      data: null,
    });
  }
});

/*
 * 删除单个用户
 */
router.delete("/user/:id", async (req, res) => {
  //获取请求 id
  let id = req.params.id;
  //判断
  if (!id) {
    return res.json({
      msg: "id参数缺失",
      code: "1004",
      data: null,
    });
  }
  try {
    //删除数据
    await UserModel.deleteOne({ _id: id });
    //响应
    return res.json({
      code: "0000",
      msg: "删除成功",
      data: null,
    });
  } catch (e) {
    return res.json({
      code: "2001",
      msg: "数据库操作失败~",
      data: null,
    });
  }
});

/**
 * 更新单个用户信息
 */
router.patch("/user/:id", (req, res) => {
  //获取请求 id
  let id = req.params.id;
  //判断
  if (!id) {
    return res.json({
      msg: "id参数缺失",
      code: "1004",
      data: null,
    });
  }
  //创建 formidable form 对象
  const form = formidable({
    multiples: true,
    // uploadDir 对应的文件夹, 需要手动创建
    uploadDir: path.resolve(__dirname, "../public/uploads"), //选择绝对路径
    keepExtensions: true, //保留文件原始的扩展名   就是文件名后缀
  });
  //解析表单数据
  form.parse(req, async (err, fields, files) => {
    if (err) {
      console.log(err);
      return res.send("错误");
    }
    try {
      //用户名格式显示 4-18 的非空白字符
      let reg = /^\S{4,18}$/;
      if (!reg.test(fields.uname)) {
        return res.json({
          code: "1002",
          msg: "用户名格式不正确",
          data: null,
        });
      }

      //插入数据库之前 检测该用户名是否已经存在
      let count = await UserModel.count({
        $and: [{ uname: fields.uname }, { _id: { $ne: id } }],
      });
      //判断
      if (count > 0) {
        return res.json({
          code: "1003",
          msg: "该用户名已经存在, 请更换",
          data: null,
        });
      }
      //将数据插入到数据库中
      let data = {
        uname: fields.uname,
      };

      if(files.profile.size > 0){
        //拼接图片的访问路径
        let filePath = files.profile.filepath;
        let profile = filePath.split("public").pop().replaceAll("\\", "/");
        data.profile = profile;
      }
      
      //更新数据库
      await UserModel.updateOne({ _id: id }, data); //UserModel.create(data, (err, data) => {})
      //响应成功的结果
      return res.json({
        code: "0000",
        msg: "更新成功",
        data: null,
      });
    } catch (e) {
      return res.json({
        code: "2001",
        msg: "数据库操作失败~",
        data: null,
      });
    }
  });
});

module.exports = router;
